package com.easy.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.common.core.domain.dto.UserHolder;
import com.easy.common.exception.CustomException;
import com.easy.common.utils.uuid.SnowFlake;
import com.easy.user.mapper.OrderMapper;
import com.easy.user.pojo.Order;
import com.easy.user.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Page<Order> page(int page, int pageSize, String name) {
        Page<Order> pageInfo = new Page<>(page, pageSize);
        //按条件查询
        LambdaQueryWrapper<Order> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, Order::getNumberId, name);//订单号
        lqw.orderByDesc(Order::getUpdateTime);//按照下单时间排序
        this.page(pageInfo, lqw);//分页数据

        return pageInfo;
    }

    @Override
    public void certificate(Long rid) {
        LocalDateTime time = LocalDateTime.now();
        SnowFlake id_ = new SnowFlake(11, 1);
        SnowFlake numberId_ = new SnowFlake(11, 8);

        long id = id_.nextId();
        long numberId = numberId_.nextId();
        Order order = new Order();
        order.setId(id);
        order.setNumberId(numberId);
        order.setUserId(UserHolder.getUser().getId());
        order.setRid(rid);
        order.setStatus(1);
        order.setCreateTime(time);
        order.setUpdateTime(time);

        try {
            orderMapper.insert(order);
        } catch (Exception e) {
            throw new CustomException("BC031");
        }
    }

    @Override
    public void deleteCertificate(Long id) {
        try {
            LambdaUpdateWrapper<Order> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Order::getId, id);
            wrapper.set(Order::getStatus, 3);
            orderMapper.update(null, wrapper);
        } catch (Exception e) {
            throw new CustomException("BC032");
        }
    }

}
